package com.guagua.chat.interfaces;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONString;

import com.guagua.chat.room.ChatRoomDao;
import com.guagua.chat.room.ChatRoomUtil;
import com.guagua.vas.constants.CacheConstants;
import com.guagua.vas.constants.ConfigConstants;
import com.guagua.vas.redis.RedIsHandlerFactory;
import com.guagua.vas.util.CacheManager;
import com.guagua.vas.util.StringUtil;

public class InterfaceAction extends HttpServlet{
	
	
	private ChatRoomDao dao=new ChatRoomDao();
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.print(getRoomInfo(Long.parseLong(request.getParameter("room_id"))));
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
        doGet(request,response);
    }
	
	/**
	 * 函数说明：获取房间基本信息 <br/>
	 * 
	 * @return 返回结果说明. （String）房间信息json串
	 */
	public String getRoomInfo(long room_id){
		List room_info = new ArrayList();
		Map<String,String> mapRoomMsg = null;
		
		String room_name="此房间名称已过期";
		
		//从缓存中查询
		room_info=(List)CacheManager.getInstance().get(ChatRoomUtil.ROOMINFO_ROOM_ID(room_id));
		if (room_info==null){
			//缓存中没有数据，从数据库中查询
			room_info=dao.getRoomInfo(room_id);
			//将结果放入缓存中，缓存时间为5分钟
			CacheManager.getInstance().put(ChatRoomUtil.ROOMINFO_ROOM_ID(room_id), room_info,(long)5,TimeUnit.MINUTES);
		}
		//从公用redis中查询房间的基本信息，主要是获取房间名称
		mapRoomMsg = RedIsHandlerFactory.getInstance().getGuaguaRoomMsgMap(room_id);
		if(mapRoomMsg!=null && mapRoomMsg.size()>0){
			room_name=mapRoomMsg.get(CacheConstants.ROOM_NAME);
		}
		
		if(room_info.size()>0){
			((HashMap)room_info.get(0)).put("name",room_name);
			((HashMap)room_info.get(0)).put("description",StringUtil.StringEncodeUtf8((String)((HashMap)room_info.get(0)).get("description")));
		}else{
			Map map=new HashMap();
			map.put("room_id",room_id);
			map.put("name", StringUtil.StringEncodeUtf8(room_name));
			map.put("imgURL", ConfigConstants.IMG_DEFAULT);
			map.put("description","");
			room_info.add(map);
		}
		JSONArray jsonArray2 = JSONArray.fromObject(room_info);
		return jsonArray2.toString();
		
	}


	
}
